package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.MemberMapper;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Transactional
public class MemberServiceImpl extends ServiceImpl<MemberMapper, Member> implements MemberService {
    @Override
    public void addNewMember(String telephone) {
        // 此方法首先判断数据库是否有此用户,没有则保存此手机用户
        QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("PHONENUMBER",telephone);
        Member member = baseMapper.selectOne(queryWrapper);
        if (member==null){
            Member newMember = new Member();
            newMember.setPhoneNumber(telephone);
            // 设置注册时间 注意:可以在数据库和实体类对应的字段设置属性为Timestamp,(数据库也有此数据类型,插入时如同主键,输入null,自动给值,精确到秒)
            newMember.setRegTime(new Date());
            save(newMember);
        }
    }

    @Override
    public Map getMemberCount() {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH,-12);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM");
        ArrayList<String> yearAndMonth = new ArrayList<>();
        ArrayList<Integer> memberCounts = new ArrayList<>();
        for (int i = 0; i < 12; i++) {
            Date date = calendar.getTime();
            String format = simpleDateFormat.format(date);
            yearAndMonth.add(format);
            String begin = format + "-01";
            String end = format + "-31";
            Integer memberCount = baseMapper.findMemberCounts(begin,end);
            memberCounts.add(memberCount);
            calendar.add(Calendar.MONTH,1);
        }
        HashMap<String, List> map = new HashMap<>();
        map.put("yearAndMonth",yearAndMonth);
        map.put("memberCounts",memberCounts);
        return map;
    }
}
